<template>
  <div class="login-container">
    <h2>会议室预订系统 - 登录</h2>
    <div class="role-select">
      <label>选择角色：</label>
      <select v-model="currentRole">
        <option value="customer">客户</option>
        <option value="employee">员工</option>
        <option value="admin">管理员</option>
      </select>
    </div>
    <form @submit.prevent="handleLogin">
      <div class="form-group">
        <label>账号：</label>
        <input type="text" v-model="form.username" required>
      </div>
      <div class="form-group">
        <label>密码：</label>
        <input type="password" v-model="form.password" required>
      </div>
      <button type="submit">登录</button>
    </form>
    <p v-if="currentRole === 'customer'">
      新用户？<router-link to="/register">点击注册</router-link>
    </p>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from '../axios';
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/UserStore';

const currentRole = ref('customer');
const form = ref({
  username: '',
  password: ''
});
const router = useRouter();
const userStore = useUserStore();

const handleLogin = async () => {
  try {
    const response = await axios.post('/users/login', {
      username: form.value.username,
      password: form.value.password,
    });
    
    const { token, user } = response.data.data;
    userStore.login(user, token);
    
    // 根据角色跳转页面
    if (user.user_type === 'customer') {
      router.push('/booking');
    } else if (user.user_type === 'employee') {
      router.push('/status');
    } else {
      router.push('/admin');
    }
  } catch (error) {
    alert(error.response?.data?.error || '登录失败，请检查账号密码');
  }
};
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}
.form-group {
  margin-bottom: 15px;
}
label {
  display: block;
  margin-bottom: 5px;
}
input {
  width: 100%;
  padding: 8px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
}
button {
  width: 100%;
  padding: 10px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>